<template>
  <el-form ref="loginFormRef" :model="loginFormState.loginForm" :rules="loginFormState.loginRules" size="large">
    <el-form-item prop="account">
      <el-input v-model="loginFormState.loginForm.account" type="text" placeholder="请输入用户名称" :disabled="inputDisabled">
        <template #prefix>
          <jxtech-svg-icon :icon="'#icon-user-fill'" :size="22"></jxtech-svg-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="loginFormState.loginForm.password"
        type="password"
        placeholder="请输入登录密码"
        show-password
        autocomplete="new-password"
        :disabled="inputDisabled"
      >
        <template #prefix>
          <jxtech-svg-icon :icon="'#icon-lock-fill'" :size="22"></jxtech-svg-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="verify" v-if="loginFormState.randomCode">
      <el-row :gutter="20">
        <el-col :span="12" style="height: 40px">
          <el-input
            v-model="loginFormState.loginForm.verify"
            type="text"
            placeholder="请输入验证码"
            maxlength="4"
            :disabled="inputDisabled"
          >
            <template #prefix>
              <jxtech-svg-icon icon="#icon-Account" :size="22"></jxtech-svg-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="12" style="height: 40px">
          <vue-img-verify ref="verifyRef" />
        </el-col>
      </el-row>
    </el-form-item>
  </el-form>
  <div class="login-btn">
    <el-button round size="large" type="primary" :loading="loading" @click="login(loginFormRef)"> 登录 </el-button>
    <el-button round size="large" type="primary" @click="SSOLogin"> SSO 登录 </el-button>
  </div>
</template>

<script setup lang="ts" name="login-form">
import { ref, reactive, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import { HOME_URL } from "@/config";
import { getTimeState } from "@/utils";
import { ElNotification } from "element-plus";
import { useUserStore } from "@/stores/modules/user";
import { useTokenStore } from "@/stores/modules/token";
import { useAuthStore } from "@/stores/modules/auth";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import vueImgVerify from "./verification-code.vue"; // 引入验证码的子组件
import type { ElForm } from "element-plus";
import { AxiosResponse } from "axios";
import { JxtechToken } from "@/stores/interface/token";

const props = defineProps({
  randomCode: {
    type: Boolean,
    default: false
  }
});
const verifyRef = ref();
const router = useRouter();
const userStore = useUserStore();
const tokenStore = useTokenStore();
const authStore = useAuthStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();

type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
// 验证码自定义验证
const validateVerify = (rule: any, value: any, callback: any) => {
  if (verifyRef.value && verifyRef.value.imgCode == loginFormState.loginForm.verify.toUpperCase()) {
    callback();
  } else {
    // 图形验证码 console.log(verifyRef.value.imgCode)
    callback(new Error("验证码错误!"));
    verifyRef.value.handleDraw();
  }
};

const loading = ref(false);
const inputDisabled = ref(false);
const loginFormState = reactive({
  loginForm: {
    verify: "",
    account: "admin",
    password: "Jxtech@123"
  },
  // 判断是否开启验证码
  randomCode: computed(() => props.randomCode),
  verifyRuleswitch: (val: boolean) => {
    if (val) {
      loginFormState.loginRules.verify = [
        {
          required: true,
          message: "请填写验证码",
          trigger: "blur"
        },
        {
          validator: validateVerify,
          trigger: "blur"
        }
      ];
    } else {
      loginFormState.loginRules.verify = [];
    }
  },
  loginRules: {
    account: [
      {
        required: true,
        message: "请填写用户名",
        trigger: "blur"
      },
      {
        min: 1,
        max: 20,
        message: "名称长度超过20字符",
        trigger: "blur"
      }
    ],
    password: [{ required: true, message: "请输入密码", trigger: "blur" }],
    // 验证码自定义验证
    verify: [
      {
        required: true,
        message: "请填写验证码",
        trigger: "blur"
      },
      {
        validator: validateVerify,
        trigger: "blur"
      }
    ]
  }
});

// login
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true;
      inputDisabled.value = true;
      try {
        /**获取token */
        const loginResponse: AxiosResponse<JxtechToken> = await userStore.login(loginFormState.loginForm);
        /**登录成功后处理 */
        userStore.loginSuccessAfter(loginResponse.data);
        /**获取用户信息 */
        await userStore.getInfo();
        /**获取菜单 */
        await authStore.getAuthMenuList();
        /**清空 tabs 数据 */
        tabsStore.setTabs([]);
        /**清空 keepAlive 数据 */
        keepAliveStore.setKeepAliveName([]);
        /**跳转到首页 */
        router.push(HOME_URL);
        ElNotification({
          title: getTimeState(),
          message: `欢迎登录 ${userStore.userFullName}`,
          type: "success",
          duration: 3000
        });
      } catch (error) {
        loginFormRef.value?.resetFields();
      } finally {
        loading.value = false;
        inputDisabled.value = false;
      }
    } else {
      console.log("error submit!", fields);
    }
    // if (!valid) return;
    // loading.value = true;
    // try {
    //   // 1.执行登录接口
    //   const { data } = await loginApi({ ...loginForm, password: md5(loginForm.password) });
    //   userStore.setToken(data.access_token);

    //   // 2.添加动态路由
    //   await initDynamicRouter();

    //   // 3.清空 tabs、keepAlive 数据
    // tabsStore.setTabs([]);
    // keepAliveStore.setKeepAliveName([]);

    //   // 4.跳转到首页
    //   router.push(HOME_URL);
    //   ElNotification({
    //     title: getTimeState(),
    //     message: "欢迎登录 Geeker-Admin",
    //     type: "success",
    //     duration: 3000
    //   });
    // } finally {
    //   loading.value = false;
    // }
  });
};

// SSO
const SSOLogin = () => {};

onMounted(() => {
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    e = (window.event as KeyboardEvent) || e;
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };
});

defineExpose({
  verifyRuleswitch: (val: boolean) => loginFormState.verifyRuleswitch(val)
});
</script>

<style scoped lang="scss">
@import "../index.scss";
</style>
